package com.example.wan_android.viewmodel

import android.content.Intent
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.map
import androidx.lifecycle.viewModelScope
import com.example.wan_android.http.bean.BannerItem
import com.example.wan_android.http.bean.PaperInfoData
import com.example.wan_android.http.code.BannerRepository
import com.example.wan_android.http.code.PaperRepository
import com.example.wan_android.ui.activity.WebActivity
import kotlinx.coroutines.launch

class PaperShowViewModel : BaseViewModel() {
    private val bannerRepository = BannerRepository()
    private val paperRepository = PaperRepository()
    private val _banners = MutableLiveData<Result<List<BannerItem>>>()
    private val _indexLiveData = MutableLiveData<Int>(0)
    val banners: MutableLiveData<Result<List<BannerItem>>> = _banners
    val nowIndex: LiveData<String> = _indexLiveData.map {
        "${it + 1}/3"
    }
    var position = 0;
    private val _paperInfoData = MutableLiveData<Result<List<PaperInfoData>>>()
    val paperInfoData: LiveData<Result<List<PaperInfoData>>> = _paperInfoData
    private val _isSuccess = MutableLiveData<Boolean>(false)
    val isSuccess = _isSuccess

    init {
        getBanners()

    }

    fun getBanners() {
        viewModelScope.launch {
            _banners.value = bannerRepository.fetchBanners()
        }
    }


    fun getPaperInfoData() {
        viewModelScope.launch {
            paperRepository.fetchPaperInfoData(
                position ?: 0, // 使用当前页码
            ).let { result ->
                if (result.isSuccess) {
                    result.getOrNull()?.let { data ->
                        if (data.isNotEmpty()) {
                            position = (position ?: 0) + 1 // 自动递增页码
                        }
                    }
                }
                _paperInfoData.value = result
                _isSuccess.value = true
            }
        }
    }

//    fun getPaperInfoData() {
//        viewModelScope.launch {
//            _paperInfoData.value = paperRepository.fetchPaperInfoData(_paperIndex.value!!)
//        }
//    }

    fun openWeb(url: String) {
        startActivity(Intent().apply {
            putExtra(WebViewModel.url, url)
        }, targetClass = WebActivity::class.java)
    }

//    fun addPaperIndex() {
//        _paperIndex.value = _paperIndex.value?.let { it + 1 }
//        getPaperInfoData()
//    }

    fun setIndex(index: Int) {
        _indexLiveData.value = index
    }


}